﻿//-----------------------------------------------------------------------
// <copyright>
//     Copyright (c) Artur Mustafin. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using Excel.Expressions.Classes;

namespace Excel.Expressions.Compiler
{
    internal class CellReferenceGroup : CellExpression
    {
        private CellReference _a;
        private CellReference _b;

        public CellReferenceGroup(CellExpression a, CellExpression b)
        {
            _a = a as CellReference;
            _b = b as CellReference;
            AddRange(Cell.GetRange(_a.Id, _b.Id));
        }

        private Func<double, double, double> _eval;

        public void Initialize(Func<double, double, double> eval)
        {
            _eval = eval;
        }

        internal IEnumerable<CellReference> References
        {
            get
            {
                foreach (CellReference reference in Children)
                {
                    yield return reference;
                }
            }
        }

#if DEBUG
        public override string ToString()
        {
            return string.Format("{0}:{1}", _a, _b);
        }
#endif
        public override double Eval()
        {
            double value = 0;
            IEnumerable<CellReference> values = References;
            IEnumerator<CellReference> enumerator = values.GetEnumerator();
            enumerator.MoveNext();
            if (enumerator.Current != null)
            {
                value = enumerator.Current;
                while (enumerator.MoveNext())
                {
                    value = _eval(value, enumerator.Current);
                }
            }
            return value;
        }
    }
}